from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.ext.asyncio import AsyncSession

from ..schemas import Token
from ..service import authenticate_user
from ..util import create_token
from ...dependents import get_db

auth_api = APIRouter()


@auth_api.post('/login', response_model=Token)
async def login(form: OAuth2PasswordRequestForm = Depends(), db: AsyncSession = Depends(get_db)):
    """
    用户登录
    :param form:
    :param db:
    :return:
    """

    user = await authenticate_user(db, form.username, form.password)
    login_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="",
        headers={'WWW-Authenticate': 'Bearer'}
    )
    if not user:
        login_exception.detail = "用户名密码错误"
        raise login_exception

    if not user.state:
        login_exception.detail = "账户已被禁用"
        raise login_exception

    # 发放令牌
    access_token = create_token(data={"username": user.username, "id": user.id})

    return {"access_token": access_token, "token_type": "bearer"}
